<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="5">
        <div style="border:1px solid #eee;min-height:calc(100vh - 150px);padding:20px 10px;min-width:200px">
          <div style="overflow: hidden">
            <el-button
              size="mini"
              type="primary"
              class="btn-add"
              @click="showDepartment('add')"
              style="float:right">
              新增分类
            </el-button>
          </div>
          <div style="margin-top:20px" v-loading="dataLoading">
            <el-tree
              :highlight-current="true"
              @node-click="nodeClick"
              :data="data"
              node-key="typeId"
              default-expand-all
              :props="props"
              :expand-on-click-node="false">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ data.typeName }}</span>
                <span>
                  <el-button
                    type="text"
                    size="mini"
                    @click.stop.native="showDepartment('edit',data)">
                    修改
                  </el-button>
                </span>
              </span>
            </el-tree>
          </div>
        </div>
      </el-col>
      <el-col :span="19">
        <div style="border:1px solid #eee;min-height: calc(100vh - 150px);padding:20px">
          <!--搜索-->
          <el-form :inline="true" :model="listQuery" size="mini" label-width="80px">
            <el-form-item label="标签名称：">
              <el-input v-model="listQuery.name" placeholder="请输入标签名称" style="width:250px"></el-input>
            </el-form-item>
            <el-form-item label="类型：">
              <el-select v-model="listQuery.type" clearable style="width:120px">
                <el-option :value="1" label="系统"></el-option>
                <el-option :value="2" label="自定义"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态：">
              <el-select v-model="listQuery.status" clearable style="width:120px">
                <el-option :value="1" label="启用"></el-option>
                <el-option :value="2" label="禁用"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="创建人：">
              <el-select v-model="listQuery.createName" filterable placeholder="请选择" clearable>
                <el-option
                  v-for="item in userOptionList"
                  :key="item.userId"
                  :label="item.realName"
                  :value="item.realName">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                @click="handleSearchList()"
                type="primary">
                查询
              </el-button>
              <el-button
                size="mini"
                type="primary"
                class="btn-add"
                @click="showDialog('add',null)">
                新增标签
              </el-button>
            </el-form-item>
          </el-form>
          <el-table ref="productTable"
                    :data="list"
                    style="width: 100%;font-size: 12px;"
                    v-loading="listLoading"
                    border>
            <el-table-column label="标签名称"  align="center" min-width="100">
              <template slot-scope="scope">{{scope.row.name}}</template>
            </el-table-column>
            <el-table-column label="标签分类"  align="center" min-width="100">
              <template slot-scope="scope">{{scope.row.typeName }}</template>
            </el-table-column>
            <el-table-column label="排序"  align="center" min-width="150">
              <template slot-scope="scope">{{scope.row.mobile}}</template>
            </el-table-column>
            <el-table-column label="类型"  align="center" min-width="100">
              <template slot-scope="scope">{{scope.row.type==1?'系统':'自定义'}}</template>
            </el-table-column>
            <el-table-column label="状态"  align="center" min-width="100">
              <template slot-scope="scope">
                <el-switch
                  @change="changeStatus(scope.row)"
                  v-model="scope.row.status"
                  :active-value="1"
                  :inactive-value="2">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="创建人"  align="center" min-width="100">
              <template slot-scope="scope">{{scope.row.createName}}</template>
            </el-table-column>

            <el-table-column label="操作"  align="center" min-width="150">
              <template slot-scope="scope">
                <el-button
                  type="text" @click="showDialog('edit',scope.row)">
                  编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              layout="total, sizes,prev, pager, next,jumper"
              :page-size="listQuery.pageSize"
              :page-sizes="[10,15,20]"
              :current-page.sync="listQuery.pageNum"
              :total="total">
            </el-pagination>
          </div>
        </div>
      </el-col>
    </el-row>


    <!--编辑标签-->
    <el-dialog
      :close-on-click-modal="false"
      :title="title2"
      :beforeClose="beforeClose2"
      :visible.sync="dialogVisible2"
      width="360px">
      <div style="max-height:500px;overflow: auto">
        <el-form :model="employForm" size="mini" label-width="100px" :rules="rules2" ref="employForm">
          <el-form-item label="标签名称：" prop="name">
            <el-input v-model="employForm.name" placeholder="标签名称" ></el-input>
          </el-form-item>
          <el-form-item label="所属分类：" prop="typeId">
            <el-cascader
              v-model="employForm.typeId"
              :options="data2"
              :props="{value:'typeId',label:'typeName',emitPath:false}"
              clearable>
            </el-cascader>
          </el-form-item>
          <el-form-item label="排序：">
            <el-input v-model="employForm.sort" style="width:100px"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose2">取 消</el-button>
          <el-button type="primary" @click="handleConfirm2" :loading="btnLoading2">确 定</el-button>
      </span>
    </el-dialog>

    <!--新增/编辑分类-->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :beforeClose="beforeClose"
      :visible.sync="dialogVisible"
      width="420px">
      <el-form :model="departmentForm" size="mini" label-width="120px" :rules="rules" ref="departmentForm">
        <el-form-item label="分类名称：" prop="typeName">
          <el-input v-model="departmentForm.typeName" placeholder="分类名称"></el-input>
        </el-form-item>
        <el-form-item label="父级：">
          <el-cascader
            v-model="departmentForm.parentId"
            :options="data2"
            :props="{ checkStrictly: true,value:'typeId',label:'typeName',emitPath:false}"
            clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="排序：">
          <el-input v-model="departmentForm.sort" style="width:100px"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {getStaffsList,postStaffsEdit,getRoleList,delSellerItem,getDeptList,saveDept,delDept,changeUserInfo} from '@/api/management'
import {productCustomersTreeTypeList,productCustomersAddType,productCustomersUpdateType,productCustomersAddTag,productCustomersUpdateTag,productCustomersTagList} from '@/api/company'
import {getUserOption,goodsLineList,listByDept} from '@/api/partner'
import {validatePhone,validateInt} from '@/utils/validate';
import store from '@/store'
const defaultListQuery = {
  name:'',
  type:'',
  status:'',
  createName:'',
  pageNum: 1,
  pageSize: 10,
};
const defaultEmployForm = {
  tagId:'',
  name:'',
  typeId:'',
  status:1,
  sort:0
};
const defaultDepartmentForm = {
  typeId:'',
  typeName:'',
  parentId:'',
  sort :0,
};
export default {
  name: "employeeSetting",
  data(){
    return{
      data : [],
      data2:[],
      props: {
        label: 'typeName',
        children: 'children'
      },
      title:'',
      title2:'',
      dialogVisible:false,
      listQuery: Object.assign({}, defaultListQuery),
      list:[],
      listLoading: false,
      total:null,
      dialogVisible2:false,
      employForm: Object.assign({}, defaultEmployForm),
      departmentForm:JSON.parse(JSON.stringify(defaultDepartmentForm)),
      rules2:{
        sort:[{required: true, message: '此项必填', trigger: 'blur'},],
        typeId:[{required: true, message: '此项必填', trigger: 'change'},],
      },
      isEdit2:false,
      rules: {
        typeName:[{required: true, message: '此项必填', trigger: 'blur'},],
      },
      options: [],
      isEdit:true,
      btnLoading:false,
      btnLoading2:false,
      dataLoading:false,
      userOptionList:[],
    }
  },
  created() {
    this.getList();
    this.getClassList();
    this.getUserOptionList();
  },
  computed: {

  },

  filters: {

  },

  methods:{
    //修改状态
    changeStatus(item){
      let pa = {};
      pa.tagId = item.tagId;
      pa.status = item.status;
      productCustomersUpdateTag(pa).then(()=>{
        this.$message({
          type: 'success',
          message: '操作成功'
        });
        this.getList();
      })
    },

    //获取员工下拉选项
    getUserOptionList(){
      getUserOption({status:1}).then((res)=>{
        this.userOptionList = res;
      })
    },
    //分类树结构点击时
    nodeClick(data){
      this.listQuery =  JSON.parse(JSON.stringify(defaultListQuery)),
      this.listQuery.typeId = data.typeId;
      this.getList()
    },

    //去除不要的children
    forTree(list){
      let newList = list;
      if(newList.length){
        for (let i = 0; i<newList.length; i++){
          if(newList[i].children && newList[i].children.length > 0){
            this.forTree(newList[i].children)
          }else{
            delete newList[i].children;
          }
        }
        return newList
      }
    },

    //获取分类列表
    getClassList(){
      this.dataLoading = true;
      productCustomersTreeTypeList({code:1}).then((res)=>{
        this.data = res;
        this.data2 = [];
        this.data2 = this.forTree(this.data);
        console.log(this.data2)
        this.dataLoading = false;
      })
    },

    //显示新增分类
    showDepartment(type,item){
      this.title = type == 'add' ? '新增分类' : '编辑分类';
      this.isEdit = type != 'add';
      if(this.isEdit){
        this.departmentForm.typeName = item.typeName;
        this.departmentForm.typeId = item.typeId;
        this.departmentForm.parentId = item.parentId;
        this.departmentForm.sort  = item.sort;
        this.departmentForm.status = item.status;
      }else{
        this.departmentForm = JSON.parse(JSON.stringify(defaultDepartmentForm));
      }
      this.dialogVisible = true;
    },
    //关闭分类弹窗之前
    beforeClose(){
      this.dialogVisible = false;
      this.$refs.departmentForm.clearValidate();
    },
    //关闭分类弹窗
    handleClose(){
      this.dialogVisible = false;
      this.$refs.departmentForm.clearValidate();
    },
    //新增/编辑分类
    handleConfirm(type,row){
      this.$refs.departmentForm.validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          let data = JSON.parse(JSON.stringify(this.departmentForm));
          data.parentId = data.parentId == '' ? 0 : data.parentId;
          data.code = 1;
          let fn = this.isEdit ? productCustomersUpdateType : productCustomersAddType;
          fn(data).then(response=>{
            this.dialogVisible = false;
            this.$refs.departmentForm.resetFields();
            this.$message({
              message: '修改成功',
              type: 'success',
              duration:1000
            });
            this.btnLoading = false;
            this.getClassList()
          }).catch(()=>{
            this.btnLoading = false;
          })
        }
      });
    },
    //删除分类
    remove(data){
      this.$confirm('确定删除分类?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delDept({ typeId:data. typeId}).then(()=>{
          this.getClassList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    //改变查看页数
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },

    //改变页码
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },

    //搜索
    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getList();
    },

    /**
     *获取列表
     **/
    getList() {
      this.listLoading = true;
      let listQuery = JSON.parse(JSON.stringify(this.listQuery));
      productCustomersTagList(listQuery).then(response => {
        this.listLoading = false;
        this.list = response.list;
        this.total = response.count;
      });
    },
    //显示标签弹窗
    showDialog(type,item){
      this.dialogVisible2 = true;
      this.title2 = type == 'add' ? '新增标签' : '编辑标签';
      if (type == 'edit'){
        this.employForm.tagId = item.tagId;
        this.employForm.name = item.name;
        this.employForm.typeId = item.typeId;
        this.employForm.status = item.status;
        this.employForm.sort = item.sort;
        console.log(this.employForm)
      }else{
        this.employForm = JSON.parse(JSON.stringify(defaultEmployForm));
      }
      this.isEdit2 = type != 'add';
    },
    //关闭标签弹窗之前
    beforeClose2(){
      this.dialogVisible2 = false;
      this.$refs.employForm.clearValidate();
    },
    //新增/编辑标签
    handleConfirm2(){
      this.$refs.employForm.validate((valid) => {
        if (valid) {
          this.btnLoading2 = true;
          let data = JSON.parse(JSON.stringify(this.employForm));
          let fn = this.isEdit2 ? productCustomersUpdateTag : productCustomersAddTag;
          fn(data).then(response=>{
            this.btnLoading2 = false;
            this.dialogVisible2 = false;
            this.$refs.employForm.resetFields();
            this.$message({
              message: '提交成功',
              type: 'success',
              duration:1000
            });
            this.getList()
          }).catch(()=>{
            this.btnLoading2 = false;
          })
        }
      });
    },
    //关闭标签弹窗
    handleClose2(){
      this.dialogVisible2 = false;
      this.$refs.employForm.clearValidate();
    },

  }

}
</script>

<style scoped lang="scss">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  padding-right: 8px;
  .el-tree-node__content{
    line-height: 30px;
  }
}
.table-product-line{
  border-top:1px solid rgb(238, 238, 238);
  border-left:1px solid rgb(238, 238, 238);
  td{
    border-bottom:1px solid rgb(238, 238, 238);
    border-right:1px solid rgb(238, 238, 238);
    line-height: 50px;
    height:50px;
    background: #fafafa;
  }

}
</style>
